import { useState } from "react";
import { useModel } from "umi";
import { v4 as uuidv4 } from "uuid";
import { Form, Input, Select, Button, message, Space } from "antd";
import { useReactive } from "ahooks";

import useCreateDepartment from "../../hooks/department/useCreateDepartment";
import useCheckDepartmentName from "../../hooks/department/useCheckDepartmentName";

const AddDepartmentModle = ({ staffs, reloadData }) => {
    const { baseInfo } = useModel("person.info");

    const { createDepartment } = useCreateDepartment();
    const { checkDepartmentName } = useCheckDepartmentName();

    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
        selectedHead: null,
    });

    let onFinish = async (values) => {
        state.loading = true;
        let variables = {
            oiUuid: uuidv4(),
            oiName: values.oiName.trim(),
            oiDesc: values.oiDesc ? values.oiDesc.trim() : "",
            oiType: "职能部门",
            maInfo: state.selectedHead || {},
            crInfo: { uuid: baseInfo.uuid, name: baseInfo.realName, time: new Date().getUTCTime() },
            pyName: pinyin(values.oiName.trim(), { toneType: "none", nonZh: "consecutive" }),
        };
        let res = await createDepartment(variables);
        if (res) {
            message.success("成功创建部门信息");
            reloadData();
            form.resetFields();
        }
        state.loading = false;
    };

    const oiNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 31) {
            let res = await checkDepartmentName(value);
            if (res === null) return Promise.reject("检查部门名称出错");
            return res > 0 ? Promise.reject("部门名称重复！") : Promise.resolve();
        } else {
            return Promise.reject("部门名称只能输入中文、英文、数字，最多30个汉字");
        }
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item label="部门名称" name="oiName" validateTrigger="onBlur" rules={[{ required: true, validator: oiNameValidator }]}>
                <Input placeholder="请输入" />
            </Form.Item>

            <Form.Item label="职责说明" name="oiDesc">
                <Input.TextArea placeholder="请输入" />
            </Form.Item>

            <Form.Item label="负责人">
                <Select
                    allowClear
                    options={staffs.map(({ osUuid, osName }) => ({ osUuid, osName }))}
                    fieldNames={{ label: "osName", value: "osUuid" }}
                    onSelect={(value, option) => (state.selectedHead = option)}
                />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={state.loading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={state.loading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default AddDepartmentModle;
